package com.locatme.fragment;

import android.app.ActionBar;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.FragmentTransaction;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.locatme.adapter.EventsViewAdapter;
import com.locatme.model.Evenement;
import com.locatme.model.Utilisateur;
import com.locatme.modelBD.EvenementBD;
import com.locatme.modelBD.ListeAmisBD;
import com.main.locatme.GetPlaces;
import com.main.locatme.JSONParser;
import com.main.locatme.R;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

public class EventsFragment extends Fragment implements View.OnClickListener, ActionBar.TabListener {
    private ViewPager pagerView;
    private EventsViewSectionAdapter eventsViewSectionAdapter;


    // declarer les variables pour afficher/saisir la date et l'heure des Time et  Date Pickers Dialog
    private int mYear, mMonth, mDay, mHour, mMinute;
    private TextView startHour, endHour, dateS, dateE, eventName, eventDesc, ident, adr;
    private final SimpleDateFormat formaterDate = new SimpleDateFormat("dd/MM/yy");
    private final SimpleDateFormat formaterHour = new SimpleDateFormat("HH:mm");
    private ImageView imgHStart, imgCalStart, imgHEnd, imgCalEnd, imgAddP;
    private Button createButton, updateButton, cancelButton;
    private CharSequence[] items;
    private ListeAmisBD amisBD;
    private List<String> listAmis, listeChecked, listInvite;
    private ArrayList<Evenement> listEvent;
    private Utilisateur user;
    private EvenementBD evenementBD;
    private boolean[] itemsChecked;
    private ListView listView;
    private EventsViewAdapter adapter;
    private List<String> valuesT = new ArrayList<String>();
    public AutoCompleteTextView userInputadr;
    public ArrayAdapter<String> adapterAutoComplete;
    private String idEvenInsere;

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_event_main, container,
                false);

        // Create the adapter that will return a fragment for each of the three primary sections
        // of the app.
        eventsViewSectionAdapter = new EventsViewSectionAdapter(this.getActivity().getSupportFragmentManager());

        // Set up the action bar.
        final ActionBar actionBar = this.getActivity().getActionBar();

        // Specify that we will be displaying tabs in the action bar.
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Set up the ViewPager, attaching the adapter and setting up a listener for when the
        // user swipes between sections.
        pagerView = (ViewPager) rootView.findViewById(R.id.pager);
        pagerView.setAdapter(eventsViewSectionAdapter);
        pagerView.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // When swiping between different app sections, select the corresponding tab.
                // We can also use ActionBar.Tab#select() to do this if we have a reference to the
                // Tab.
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < eventsViewSectionAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by the adapter.
            // Also specify this Activity object, which implements the TabListener interface, as the
            // listener for when this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(eventsViewSectionAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
        return rootView;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        final ActionBar actionBar = this.getActivity().getActionBar();
        actionBar.removeAllTabs();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in the ViewPager.
        pagerView.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onClick(View view) {

    }

    public class EventsViewSectionAdapter extends FragmentStatePagerAdapter {

        public EventsViewSectionAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int i) {
            switch (i) {
                case 0:
                    return new CreateEventSectionFragment();
                case 1:
                    return new ViewEventSectionFragment();

                default:
                    return new CreateEventSectionFragment();
            }
        }

        @Override
        public int getItemPosition(Object object) {
            return PagerAdapter.POSITION_NONE;
        }

        @Override
        public int getCount() {
            return 2;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            String s = null;
            if (position == 0) {
                s = "Create Events";
            }
            if (position == 1) {
                s = "My Events";
            }
            if (position == 2) {
                s = "Upcomming Events";
            }
            return s;
        }
    }

    public class CreateEventSectionFragment extends Fragment implements View.OnClickListener {

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_event_creation, container, false);
            user = (Utilisateur) getActivity().getIntent().getExtras().getParcelable("user");

            startHour = (TextView) rootView.findViewById(R.id.textStartHour);
            endHour = (TextView) rootView.findViewById(R.id.textEndHour);
            dateE = (TextView) rootView.findViewById(R.id.textCalE);
            dateS = (TextView) rootView.findViewById(R.id.textCalS);
            adr = (TextView) rootView.findViewById(R.id.textadr);
            ident = (TextView) rootView.findViewById(R.id.textView3);
            createButton = (Button) rootView.findViewById(R.id.buttonCreateEvent);
            updateButton = (Button) rootView.findViewById(R.id.buttonUpdateEvent);
            cancelButton = (Button) rootView.findViewById(R.id.buttonCancelEvent);
            eventName = (TextView) rootView.findViewById(R.id.editEventName);
            eventDesc = (TextView) rootView.findViewById(R.id.editdescription);
            imgHStart = (ImageView) rootView.findViewById(R.id.imageClockS);
            imgHEnd = (ImageView) rootView.findViewById(R.id.imageClockE);
            imgCalStart = (ImageView) rootView.findViewById(R.id.imageCalS);
            imgCalEnd = (ImageView) rootView.findViewById(R.id.imageCalE);
            imgAddP = (ImageView) rootView.findViewById(R.id.imageAddPerson);
            eventName.setOnClickListener(this);
            eventDesc.setOnClickListener(this);
            imgHStart.setOnClickListener(this);
            imgHEnd.setOnClickListener(this);
            imgCalStart.setOnClickListener(this);
            adr.setOnClickListener(this);
            imgCalEnd.setOnClickListener(this);
            imgAddP.setOnClickListener(this);
            createButton.setOnClickListener(this);
            updateButton.setOnClickListener(this);
            cancelButton.setOnClickListener(this);
            listeChecked = new ArrayList<String>();
            listEvent = new ArrayList<Evenement>();
            listAmis = new ArrayList<String>();
            initEventForm();
            majListeEvents();

            return rootView;
        }

        @Override
        public void onClick(View v) {
            if (v.equals(eventName)) {
                // récupérer prompteventadressadress.xml
                LayoutInflater li = LayoutInflater.from(this.getActivity());
                View promptsView = li.inflate(R.layout.prompteventname, null);


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        this.getActivity());
                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);
                userInput.setText(eventName.getText());
                // afficher promptseventadress.xmltadress.xml dans le builder
                alertDialogBuilder.setView(promptsView);

                // définir message de la boite de dialogue
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // afficher le nom saisie
                                        eventName.setText(userInput.getText());
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // creer la boite de dialogue
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }
            if (v.equals(imgCalStart) || v.equals(imgCalEnd)) {
                final View actualV = v;
                // Récupération de la date courante
                final Calendar c = Calendar.getInstance();
                mYear = c.get(Calendar.YEAR);
                mMonth = c.get(Calendar.MONTH);
                mDay = c.get(Calendar.DAY_OF_MONTH);

                // Lancer Date Picker Dialog
                DatePickerDialog dpd = new DatePickerDialog(this.getActivity(),
                        new DatePickerDialog.OnDateSetListener() {

                            @Override
                            public void onDateSet(DatePicker view, int year,
                                                  int monthOfYear, int dayOfMonth) {
                                // Afficher la date selectionné dans le dialog
                                if (actualV.equals(imgCalStart)) {
                                    c.set(year, monthOfYear, dayOfMonth);
                                    dateS.setText(formaterDate.format(c.getTime()));
                                } else {
                                    c.set(year, monthOfYear, dayOfMonth);
                                    dateE.setText(formaterDate.format(c.getTime()));
                                }
                            }
                        }, mYear, mMonth, mDay);
                dpd.show();
            }

            if (v.equals(imgHStart) || v.equals(imgHEnd)) {
                final View actualV = v;
                // Récupération de l'heure courante
                final Calendar c = Calendar.getInstance();
                mHour = c.get(Calendar.HOUR_OF_DAY);
                mMinute = c.get(Calendar.MINUTE);

                // Lancer Time Picker Dialog
                TimePickerDialog tpd = new TimePickerDialog(this.getActivity(),
                        new TimePickerDialog.OnTimeSetListener() {

                            @Override
                            public void onTimeSet(TimePicker view, int hourOfDay,
                                                  int minute) {
                                // Afficher l'heure selectionné dans le dialog
                                if (actualV.equals(imgHStart)) {
                                    c.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, hourOfDay, minute);
                                    startHour.setText(formaterHour.format(c.getTime()));
                                } else {
                                    c.set(Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, hourOfDay, minute);
                                    endHour.setText(formaterHour.format(c.getTime()));
                                }
                            }
                        }, mHour, mMinute, true);
                tpd.show();
            }

            if (v.equals(eventDesc)) {
                // récupérer prompteventdescription.xml
                LayoutInflater li = LayoutInflater.from(this.getActivity());
                View promptsView = li.inflate(R.layout.prompteventdescription, null);


                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        this.getActivity());
                final EditText userInput = (EditText) promptsView
                        .findViewById(R.id.editTextDialogUserInput);
                userInput.setText(eventDesc.getText());
                // afficher prompteventdescription.xmltadress.xml dans le builder
                alertDialogBuilder.setView(promptsView);

                // définir message de la boite de dialogue
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // afficher la description saisie
                                        eventDesc.setText(userInput.getText());
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // creer la boite de dialogue
                AlertDialog alertDialog = alertDialogBuilder.create();

                // show it
                alertDialog.show();
            }

            if (v.equals(adr)) {
                // récupérer promptseventadress.xmltadress.xml
                LayoutInflater li = LayoutInflater.from(this.getActivity());
                View promptsView = li.inflate(R.layout.promptseventadress, null);
                adapterAutoComplete = new ArrayAdapter<String>(this.getActivity(), R.layout.itemautocompletelist, R.id.itemList);

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        this.getActivity());
                userInputadr = (AutoCompleteTextView) promptsView
                        .findViewById(R.id.editTextDialogUserInput);
                userInputadr.setText(adr.getText());
                adapterAutoComplete.setNotifyOnChange(true);
                userInputadr.setAdapter(adapterAutoComplete);
                userInputadr.addTextChangedListener(new TextWatcher() {

                    @Override
                    public void beforeTextChanged(CharSequence charSequence, int i, int i2, int i3) {
                        adapterAutoComplete.clear();
                        GetPlaces task = new GetPlaces(EventsFragment.this);
                        //now pass the argument in the textview to the task
                        task.execute(userInputadr.getText().toString());
                    }

                    public void onTextChanged(CharSequence s, int start, int before, int count) {
                        if (count % 3 == 1) {
                            adapterAutoComplete.clear();
                            GetPlaces task = new GetPlaces(EventsFragment.this);
                            //now pass the argument in the textview to the task
                            task.execute(userInputadr.getText().toString());
                        }
                    }

                    @Override
                    public void afterTextChanged(Editable editable) {

                    }
                });

                // afficher promptseventadress.xmltadress.xml dans le builder
                alertDialogBuilder.setView(promptsView);

                // définir message de la boite de dialogue
                alertDialogBuilder
                        .setCancelable(false)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        // afficher l'adresse saisie
                                        adr.setText(userInputadr.getText());
                                    }
                                })
                        .setNegativeButton("Cancel",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int id) {
                                        dialog.cancel();
                                    }
                                });

                // creer la boite de dialogue
                AlertDialog alertDialog = alertDialogBuilder.create();
                alertDialog.getWindow().setGravity(Gravity.TOP);
                // show it
                alertDialog.show();
            }

            if (v.equals(imgAddP)) {
                if (listAmis != null) {
                    AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
                    builder.setTitle("Choose your guest:");
                    builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            for (int i = 0; i < items.length; i++) {
                                if (itemsChecked[i]) {
                                    listeChecked.add(items[i].toString());
                                }
                            }
                        }
                    });
                    builder.setMultiChoiceItems(items, itemsChecked, new DialogInterface.OnMultiChoiceClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                            itemsChecked[which] = isChecked;
                        }
                    });
                    builder.show();
                } else {
                    Toast.makeText(this.getActivity(), "You don't have any friends", Toast.LENGTH_LONG).show();
                }
            }

            if (v.equals(createButton)) {

                if (!eventName.getText().toString().equals("Event Name") && !adr.getText().toString().equals("Adress") && !adr.getText().toString().equals("") && !eventName.getText().toString().equals("")) {
                    Evenement evenement = new Evenement(eventName.getText().toString(),eventDesc.getText().toString(), adr.getText().toString(), dateS.getText().toString(), dateE.getText().toString(), startHour.getText().toString(), endHour.getText().toString(), user.getLogin());
                    evenementBD = new EvenementBD(this.getActivity());
                    evenementBD.open();
                    evenementBD.insertEvenement(evenement);
                    for (String s : listeChecked)
                        evenementBD.insertinvite((int) evenementBD.getId(), s);
                    evenementBD.close();
                    CreateEvent createEvent = new CreateEvent();
                    createEvent.setContext(EventsFragment.this.getActivity());
                    createEvent.execute(eventName.getText().toString(), eventDesc.getText().toString(), adr.getText().toString(), dateS.getText().toString(), dateE.getText().toString(), startHour.getText().toString(), endHour.getText().toString(), user.getLogin());
                    Toast.makeText(this.getActivity(), "Event created", Toast.LENGTH_LONG).show();
                    initEventForm();
                    majListeEvents();
                } else {
                    Toast.makeText(this.getActivity(), "Missing Event infos", Toast.LENGTH_LONG).show();

                }
            }
            if (v.equals(updateButton)) {

                if (!adr.getText().toString().equals("") && !eventName.getText().toString().equals("")) {
                    Evenement evenement = new Evenement(Integer.parseInt(ident.getText().toString()), eventName.getText().toString(),eventDesc.getText().toString(), adr.getText().toString(), dateS.getText().toString(), dateE.getText().toString(), startHour.getText().toString(), endHour.getText().toString(), user.getLogin());
                    evenementBD = new EvenementBD(this.getActivity());
                    evenementBD.open();
                    evenementBD.setEvenement(evenement);
                    if (listeChecked != null) {
                        for (String s : listeChecked) {

                            if (listInvite != null) {
                                if (!listInvite.contains(s)) {

                                    evenementBD.insertinvite(Integer.parseInt(ident.getText().toString()), s);
                                }
                            } else if (listInvite == null) {

                                evenementBD.insertinvite(Integer.parseInt(ident.getText().toString()), s);
                            }
                        }
                    }
                    evenementBD.close();
                    Toast.makeText(this.getActivity(), "Event updated", Toast.LENGTH_LONG).show();
                    majListeEvents();
                    initEventForm();
                } else {
                    Toast.makeText(this.getActivity(), "Missing Event infos", Toast.LENGTH_LONG).show();

                }
            }
            if (v.equals(cancelButton)) {
                initEventForm();
            }
        }

    }

    public class ViewEventSectionFragment extends Fragment {
        private AlertDialog.Builder builder;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            final View rootView = inflater.inflate(R.layout.fragment_event_list, container, false);

            // utiliser la disposition perso définie dans l'adapter
            listView = (ListView) rootView.findViewById(R.id.list);
            adapter = new EventsViewAdapter(this.getActivity(), valuesT);
            listView.setAdapter(adapter);
            listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                    initEventForm();
                    eventName.setText(listEvent.get(i).getIntitule());
                    eventDesc.setText(listEvent.get(i).getDescription());
                    adr.setText(listEvent.get(i).getAdresse());
                    dateS.setText(listEvent.get(i).getDateDebut());
                    dateE.setText(listEvent.get(i).getDateFin());
                    startHour.setText(listEvent.get(i).gethDebut());
                    endHour.setText(listEvent.get(i).gethFin());
                    ident.setText("" + listEvent.get(i).getId());
                    listInvite = listEvent.get(i).getListAmis();
                    if (listInvite != null) {
                        for (String s : listInvite) {
                            if (listAmis.contains(s)) {
                                itemsChecked[listAmis.indexOf(s)] = true;
                            }
                        }
                    }
                    createButton.setVisibility(View.INVISIBLE);
                    updateButton.setVisibility(View.VISIBLE);
                    pagerView.setCurrentItem(0);
                }
            });
            listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {

                @Override
                public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {
                    DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            switch (which) {
                                case DialogInterface.BUTTON_POSITIVE:
                                    evenementBD.open();
                                    evenementBD.deleteEvenement(listEvent.get(i).getId());
                                    evenementBD.close();
                                    initEventForm();
                                    majListeEvents();
                                    break;
                                case DialogInterface.BUTTON_NEGATIVE:
                                    break;
                            }
                        }
                    };
                    builder = new AlertDialog.Builder(rootView.getContext());
                    builder.setMessage("Are you sure to delete event " + listEvent.get(i).getIntitule() + "?").setPositiveButton("Yes", dialogClickListener).setNegativeButton("No", dialogClickListener).show();
                    return true;
                }
            });
            return rootView;
        }
    }


    public ListeAmisBD getAmisBD() {
        return amisBD;
    }

    public void setAmisBD(ListeAmisBD amisBD) {
        this.amisBD = amisBD;
    }

    public void majListeEvents() {
        evenementBD = new EvenementBD(this.getActivity());
        evenementBD.open();
        if (listEvent != null) {
            listEvent.clear();
        }
        valuesT.clear();
        listEvent = evenementBD.recupEvenementCree(user.getLogin());
        evenementBD.close();

        if (listEvent != null) {
            for (Evenement event : listEvent) {
                valuesT.add(event.getIntitule());
            }
        }
        if (itemsChecked != null) {
            for (int i = 0; i < itemsChecked.length; i++) {
                itemsChecked[i] = false;
            }
        }
        if (adapter != null) {
            adapter.notifyDataSetChanged();
        }
        ident.setText("");
    }

    public void initEventForm() {

        final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);
        mHour = c.get(Calendar.HOUR_OF_DAY);
        mMinute = c.get(Calendar.MINUTE);
        startHour.setText(formaterHour.format(c.getTime()));
        endHour.setText(formaterHour.format(c.getTime()));
        dateS.setText(formaterDate.format(c.getTime()));
        dateE.setText(formaterDate.format(c.getTime()));

        setAmisBD(new ListeAmisBD(getActivity()));
        getAmisBD().open();
        listAmis = getAmisBD().getFriendByLogin(user.getLogin());
        if (listAmis != null) {
            items = listAmis.toArray(new CharSequence[listAmis.size()]);
            itemsChecked = new boolean[items.length];
        }
        if (itemsChecked != null) {
            for (int i = 0; i < itemsChecked.length; i++) {
                itemsChecked[i] = false;
            }
        }
        eventName.setText("");
        eventDesc.setText("");
        adr.setText("");
        ident.setText("");
        updateButton.setVisibility(View.INVISIBLE);
        createButton.setVisibility(View.VISIBLE);
    }


    public class CreateEvent extends AsyncTask<String, String, String> {
        private FragmentActivity context;
        private static final String TAG_SUCCESS = "success";
        private JSONParser jsonParser = new JSONParser();
        private static final String url_connect = "http://locatme.alwaysdata.net/locateme/create_event.php";

        public void setContext(FragmentActivity context) {
            this.context = context;
        }


        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... strings) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("intitule", strings[0]));
            params.add(new BasicNameValuePair("description", strings[1]));
            params.add(new BasicNameValuePair("adresse", strings[2]));
            params.add(new BasicNameValuePair("dateDebut", strings[3]));
            params.add(new BasicNameValuePair("dateFin", strings[4]));
            params.add(new BasicNameValuePair("hDebut", strings[5]));
            params.add(new BasicNameValuePair("hFin", strings[6]));
            params.add(new BasicNameValuePair("loginPersonne", strings[7]));
            JSONObject json = jsonParser.makeHttpRequest(url_connect,
                    "POST", params);


            try {
                idEvenInsere = json.getString("idEvenInsere");
                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    context.runOnUiThread(new Runnable() {
                        public void run() {

                        }
                    });

                } else {
                    context.runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(context, " Enregistrement échoué ", Toast.LENGTH_LONG).show();
                        }
                    });
                }
            } catch (JSONException e) {

                Log.d("Exeception de json : ", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {

        }
    }

    public class InserInvit extends AsyncTask<String, String, String> {
        private FragmentActivity context;
        private static final String TAG_SUCCESS = "success";
        JSONParser jsonParser = new JSONParser();
        private static final String url_connect = "http://locatme.alwaysdata.net/locateme/insert_invite.php";

        public void setContext(FragmentActivity context) {
            this.context = context;
        }


        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(String... strings) {
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("idEven", strings[0]));
            params.add(new BasicNameValuePair("invite", strings[1]));
            JSONObject json = jsonParser.makeHttpRequest(url_connect,
                    "POST", params);


            try {

                int success = json.getInt(TAG_SUCCESS);

                if (success == 1) {

                    context.runOnUiThread(new Runnable() {
                        public void run() {

                        }
                    });

                } else {
                    context.runOnUiThread(new Runnable() {
                        public void run() {

                            Toast.makeText(context, " Enregistrement échoué ", Toast.LENGTH_LONG).show();
                        }
                    });

                }
            } catch (JSONException e) {

                Log.d("Exeception de json : ", e.toString());
            }
            return null;
        }

        @Override
        protected void onPostExecute(String s) {
        }
    }
}





